/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
Components.utils.import("resource://gre/modules/DbTerminal.jsm");
Components.utils.import("resource://gre/modules/k9mailDb.jsm");
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);


function testjinhai()
{
    alert(122456);
    
}
/*字符转码UTF-8,主要用于读文件*/
function convertToUnicode(aStr) {  
  try {  
   var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]  
     .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);  
   converter.charset = "UTF-8";  //GB180380
   var content = converter.ConvertToUnicode(aStr);  
  
   return content;  
  } catch (e) {  
  }  
 }  
/*字符转码，主要用于写文件*/
function convertFromUnicode(aStr) {  
  try {   
  var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]  
                           .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);  
   converter.charset = "UTF-8";// 或者"GB2312"  
   var content = converter.ConvertFromUnicode(aStr);  
   return content;  
  } catch (e) {  
  }  
 }  
/*解析存储在本地的XML数据*/
function parserLocalFile(fileName,onDev) 
{
    //fileName="test-002.xml";
    //alert('aaaaa');
     //(111);
    Components.utils.import("resource://gre/modules/FileUtils.jsm");
    Components.utils.import("resource://gre/modules/NetUtil.jsm");     
    var filetmp = FileUtils.getFile("ProfD", [fileName]);
    try
    {
    //var file = FileUtils.getFile("TmpD", [fileName]);    
   // alert(fileName); 
    //var file = FileUtils.getFile("TmpD", [fileName]);
    var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
    //alert(121);
    inputStream.init(filetmp, -1, 0, 0);
    //alert(123);
    //file.remove(true);
    //alert(onDev);
    var dataString = NetUtil.readInputStreamToString(inputStream, inputStream.available());
    //alert(124);
    var data=convertToUnicode(dataString);
    //alert(125);
    var parser = new DOMParser();
    var xmldom = parser.parseFromString(data,"application/xml");
    //alert(126);
    filetmp.remove(true);
    //alert(127);
    /*解析XML文件*/
    if(fileName==="contacts.xml")
    {
       //filetmp.remove(true);
       var accNodes=xmldom.documentElement.childNodes; 
   
       var contactInfo=[{cContactName: "联系人姓名", cEmailAddress: "邮箱地址", cDeviceName:"通讯录名",cAccount:"所属账户"}];
      
       dDeviceSqlite.onLoad();
       var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT count(cId) AS numbers FROM td_contact WHERE cDeviceName = :myVal");
                  statement.params.myVal = onDev;
                 
        try {
                 while (statement.executeStep()) {
                      var  ifhavedev = statement.row.numbers;
                      }
                   }
                 
        finally {
                  statement.reset();
                }

        if (ifhavedev !==0)
        {
//             var statement = dDeviceSqlite.dbConnection.createStatement("UPDATE td_contact \
//                           SET cStatus = :myVal1  where cDeviceName = :myVal");
//      statement.params.myVal = devicen;
//      statement.params.myVal1 = 3;
//      try {
//        while (statement.executeStep()) {
//            continue;
//        }
//      }
//    finally {
//        statement.reset();
//    }
            
            
            var statement = dDeviceSqlite.dbConnection.createStatement("\
                  DELETE FROM td_contact WHERE cDeviceName = :myVal");
            statement.params.myVal = onDev;
            try{
                 while(statement.executeStep()){
                    continue;
                }
            }
            finally{
                statement.reset();
            }
        }
       for(var i=0;i<accNodes.length;i++)
       {
           var accName=xmldom.getElementsByTagName("phone")[i].childNodes[0].nodeValue.split(";")[0];
           //var accName=xmldom.getElementsByTagName("account")[i].childNodes[0].nodeValue.split(";")[0];
           var contactName=xmldom.getElementsByTagName("contact")[i].childNodes[0].nodeValue.split(";")[0];
           var emailAddress=xmldom.getElementsByTagName("email")[i].childNodes[0].nodeValue.split(";")[0];
           var dirName=onDev;
           contactInfo.push({cContactName: contactName, cEmailAddress:emailAddress, cDeviceName:dirName,cAccount:accName});
       }
       //(contactInfo.length);
      var statement = dDeviceSqlite.dbConnection.createStatement("\
                                   INSERT INTO td_contact(cDeviceName,cContactName,cEmailAddress, cAccount) \
                                   VALUES (:cDeviceName,:cContactName, :cEmailAddress, :cAccount)");
        var params = statement.newBindingParamsArray();
        for(var i=1;i<contactInfo.length;i++){
            var bp = params.newBindingParams();
            bp.bindByName("cDeviceName",contactInfo[i].cDeviceName);
            bp.bindByName("cContactName",contactInfo[i].cContactName);
            bp.bindByName("cEmailAddress",contactInfo[i].cEmailAddress);
            bp.bindByName("cAccount",contactInfo[i].cAccount);
            //bp.bindByName("cDiruri",contactInfo[i].cDiruri);
            params.addParams(bp);
        }
        statement.bindParameters(params);
        statement.executeAsync({handleCompletion:function(aReason){
                while(1){
                    if(aReason !==Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED){
                        continue;
                    }else{
                        break;   
                    }
                }
        }});
        statement.finalize();
        
    }else{
       //alert(12344);
       //filetmp.remove(true);
       dDeviceSqlite.onLoad();
       var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dId FROM td_device WHERE dName = :myVal");
                  statement.params.myVal = onDev;
                 
        try {
                 while (statement.executeStep()) {
                      var  cdId = statement.row.dId;
                      }
                   }
                 
        finally {
                  statement.reset();
                }  
       //alert(12345);         
       var mailHeadInfo=[{eMessageId: "邮件ID", dId:"设备ID",eSubject: "主题", eFrom:"发件人",eTo: "收件人", eReply: "回复人",eFolder:"邮件夹",eName:"账户",eDate:"日期"}];
       //var mailcounts=xmldom.getElementsByTagName("uid"); 
       var emailNodes=xmldom.documentElement.childNodes; 
       //alert("emailNodes="+emailNodes[1].nodeName.split('_')[1]);
       for(var i=0;i<emailNodes.length;i++ )
       {
            var  hid=emailNodes[i].nodeName.split('_')[1];//xmldom.getElementsByTagName("uid")[i].childNodes[0].nodeValue;
            var  hsubject=xmldom.getElementsByTagName("subject")[i].childNodes[0].nodeValue;
            var  hsender=xmldom.getElementsByTagName("sender_list")[i].childNodes[0].nodeValue;
            var  hto=xmldom.getElementsByTagName("to_list")[i].childNodes[0].nodeValue;
            var  hreply=xmldom.getElementsByTagName("reply_to_list")[i].childNodes[0].nodeValue;
            var  hfolder=xmldom.getElementsByTagName("folder_id")[i].childNodes[0].nodeValue;
            var  haname=xmldom.getElementsByTagName("aname")[i].childNodes[0].nodeValue;
            var hdate=xmldom.getElementsByTagName("date")[i].childNodes[0].nodeValue;
            mailHeadInfo.push({eMessageId: hid,dId: cdId,eSubject: hsubject, eFrom:hsender,eTo: hto, eReply: hreply,eFolder:hfolder,eName:haname,eDate:hdate});
       }
       //alert(cdId);  
       //alert("aaaa"+mailHeadInfo.length);
       dDeviceSqlite.onLoad();
       var statement = dDeviceSqlite.dbConnection.createStatement("\
       SELECT count(eId) AS numbers FROM td_email WHERE eName = :myVal AND dId = :myVal1");
            //alert(fileName);
       var accountNS=fileName.split("_")[0];      
       //alert("aaa"+accountNS);
       statement.params.myVal =accountNS ;
       statement.params.myVal1 =cdId ;        
       try {
                 while (statement.executeStep()) {
                      var  ifhaveacc = statement.row.numbers;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
         //alert(12347);  
        if (ifhaveacc!==0)
        {
            var statement = dDeviceSqlite.dbConnection.createStatement("\
                  DELETE FROM td_email WHERE eName = :myVal and dId = :myVal1");
            statement.params.myVal = accountNS;
            statement.params.myVal1 = cdId;
           //alert("bbbb"+accountNS);
            try{
                 while(statement.executeStep()){
                    continue;
                }
            }
            finally{
                statement.reset();
            }
        }
        //alert(12348);  
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                                   INSERT INTO td_email(eMessageId,eSubject,eFrom, eTo, eReply,eFolder,eName,eDate,dId) \
                                   VALUES (:eMessageId,:eSubject, :eFrom, :eTo, :eReply,:eFolder,:eName,:eDate,:dId)");
        var params = statement.newBindingParamsArray();
        for(var i=1;i<mailHeadInfo.length;i++){
            var bp = params.newBindingParams();
            bp.bindByName("eMessageId",mailHeadInfo[i].eMessageId);
            bp.bindByName("eSubject",mailHeadInfo[i].eSubject);
            bp.bindByName("eFrom",mailHeadInfo[i].eFrom);
            bp.bindByName("eTo",mailHeadInfo[i].eTo);
            bp.bindByName("eReply",mailHeadInfo[i].eReply);
            bp.bindByName("eFolder",mailHeadInfo[i].eFolder);
            bp.bindByName("eName",mailHeadInfo[i].eName);
            bp.bindByName("eDate",mailHeadInfo[i].eDate);
            bp.bindByName("dId",mailHeadInfo[i].dId);
            params.addParams(bp);
        }
        statement.bindParameters(params);
        statement.executeAsync({handleCompletion:function(aReason){
                while(1){
                    if(aReason !==Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED){
                        continue;
                    }else{
                        break;   
                    }
                }
        }});
        statement.finalize();
        //dDeviceSqlite.onClose();
        //alert(12348); 
        //alert(mailHeadInfo.length);
    }
    
    }catch(e){
        //alert("error");
        //filetmp.remove(true);
    }

}
/*
 * 创建备份文件所在文件夹
 * @driName:对应设备名称
 * @fileName:设备信息或账户信息
 * */
function backUpToFile(driName,fileName,data)
{
    Components.utils.import("resource://gre/modules/FileUtils.jsm");
    Components.utils.import("resource://gre/modules/NetUtil.jsm");
    //Components.utils.import("resource://gre/modules/FileUtils.jsm");

    var dir = FileUtils.getDir("Home", [driName], true);
    var dirPath=dir.path;
    var file = new FileUtils.File(dirPath);
    file.append(fileName);
    prompts.alert(null, "信息备份", "数据信息备份成功"+"\n"+"文件所在路径："+file.path);
    //alert("数据信息备份成功"+"\n"+"文件所在路径："+file.path);
    var ostream = FileUtils.openSafeFileOutputStream(file);

    var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
                createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
    converter.charset = "UTF-8";
  
    var istream = converter.convertToInputStream(data);
 
    NetUtil.asyncCopy(istream, ostream, function(status) {
    if (!Components.isSuccessCode(status)) {
    alert("写入数据错误");
    return;
  }else{
    //alert("write date success");
 }
});
}

function parserLocalEmailFile(fileName)
{
     //alert(fileName); 
    Components.utils.import("resource://gre/modules/FileUtils.jsm");
    Components.utils.import("resource://gre/modules/NetUtil.jsm");     
    
    try
    {
      var filetmp = FileUtils.getFile("TmpD", [fileName]);  
      var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
      inputStream.init(filetmp, -1, 0, 0);
      var dataString = NetUtil.readInputStreamToString(inputStream, inputStream.available());
      var data=convertToUnicode(dataString);
      var parser = new DOMParser();
      var xmldom = parser.parseFromString(data, "application/xml");
      var html_content = xmldom.getElementsByTagName("html_content")[0].childNodes[0].nodeValue;
      filetmp.remove(true);
      return html_content;
    }catch(e)
    {
        alert("error");
    }
}   


 /*解析存储在本地同步的XML数据*/
function parserSyncLocalFile(fileName,deviceName,accoutName) 
{
    alert("start sync...");
    Components.utils.import("resource://gre/modules/FileUtils.jsm");
    Components.utils.import("resource://gre/modules/NetUtil.jsm");  
    var filetmp = FileUtils.getFile("TmpD", [fileName]);
    var aXml = null;
    try
    {
        var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
        inputStream.init(filetmp, -1, 0, 0);
        var dataString = NetUtil.readInputStreamToString(inputStream, inputStream.available());
        var data = convertToUnicode(dataString);
        var parser = new DOMParser();
        var xmldom = parser.parseFromString(data, "application/xml");
        var parentNodes = xmldom.documentElement.childNodes;
        var statement = dDeviceSqlite.dbConnection.createStatement("\
        SELECT dId FROM td_device WHERE dName = :myVal");
        statement.params.myVal = deviceName;   
        var deviceId = null;
        try
        {
            while(statement.executeStep())
            {
                deviceId = statement.row.dId;
                continue;
            }
        }
        finally
        {
            statement.reset();
        }
//        alert("deviceId: "+deviceId);
        statement = dDeviceSqlite.dbConnection.createStatement("\
        SELECT aName,aXml FROM td_account WHERE dId = :myVal");
        statement.params.myVal = deviceId;   
        var aName = null;
       
        try
        {
            while(statement.executeStep())
            {
                aName = statement.row.aName;
                if(aName === accoutName)
                {
                    aXml = statement.row.aXml;
                }
                continue;
            }
        }
        finally
        {
            statement.reset();
        }
//        alert("eName: "+aXml.split("_")[0]);
        for(var i = 0;i < parentNodes.length;i++)
        {
            var childNodes = parentNodes[i].childNodes;
            if(parentNodes[i].nodeName === "recv_MODIFY")
            {
                for(var j = 0;j < childNodes.length;j ++)
                {
                    var emailId = childNodes[j].id;
//                    alert("modify : "+childNodes[j].nodeName+"--: "+childNodes[j].id);
                    var eSubject = null;
                    var eSenderList = null;
                    var eToList = null;
                    var eReplyToList = null;
                    var eDate = null;
                    var eRead = null;
                    var eFolderId = null;
                   // alert("name: "+childNodes[j].getElementsByTagName("sender_list").nodeValue);
                   // alert("count: "+childNodes[j].childElementCount);
                    for(var x = 0; x < childNodes[j].childElementCount;x++)
                    {
                        var nodeValue = childNodes[j].childNodes[x].childNodes[0].nodeValue;
                        var nodeName = childNodes[j].childNodes[x].nodeName;
                        switch(nodeName)
                        {
                            case "subject" : eSubject = nodeValue; 
                                break;
                            case "sender_list" : eSenderList = nodeValue;
                                break;
                            case "to_list" : eToList = nodeValue;
                                break;
                            case "reply_to_list" : eReplyToList = nodeValue;
                                break;
                            case "date" : eDate = nodeValue;
                                break;
                            case "read" : eRead = nodeValue;
                                break;
                            case "folder_id" : eFolderId = nodeValue;
                                break;
                            
                        }
//                        alert("n: "+childNodes[j].childNodes[x].nodeName);
//                        alert("l:"+childNodes[j].childNodes.length);
//                        alert("v: "+childNodes[j].childNodes[x].childNodes[0].nodeValue);
                    }
//                    alert("eSubject: "+eSubject);
//                    alert("folder_id: "+eFolderId);
//                    alert("add emailId::::  "+emailId);
                    statement = dDeviceSqlite.dbConnection.createStatement("\
                    SELECT eId,eMessageId FROM td_email WHERE eName = :myVal");
                    statement.params.myVal = aXml.split("_")[0];   
                   //alert("cvx: "+statement.params.myVal);
                    var eMessageId = null;
                    var addEmailFlag = null;
                    try
                    {
                        while(statement.executeStep())
                        {
                            eMessageId = statement.row.eMessageId;
                            if(eMessageId === emailId)
                            {
                                addEmailFlag = "not";
//                                alert("eMessageIdccc: "+eMessageId);
                                break;
                            }
                            continue;
                        }
                    }
                    finally
                    {
                        statement.reset();
                    }
                    if(addEmailFlag === null)
                    {
                        var statement = dDeviceSqlite.dbConnection.createStatement("\
                                   INSERT INTO td_email(eMessageId,eSubject,eFrom, eTo, eReply,eFolder,eName,eDate,dId) \
                                   VALUES (:eMessageId,:eSubject, :eFrom, :eTo, :eReply,:eFolder,:eName,:eDate,:dId)");
                        var params = statement.newBindingParamsArray();
                        var bp = params.newBindingParams();
                        bp.bindByName("eMessageId",emailId);
                        bp.bindByName("eSubject",eSubject);
                        bp.bindByName("eFrom",eSenderList);
                        bp.bindByName("eTo",eToList);
                        bp.bindByName("eReply",eReplyToList);
                        bp.bindByName("eFolder",eFolderId);
                        bp.bindByName("eName",aXml.split("_")[0]);
                        bp.bindByName("eDate",eDate);
                        bp.bindByName("dId",deviceId);
                        params.addParams(bp);
                        statement.bindParameters(params);
                        statement.executeAsync({handleCompletion:function()
                        {
                          Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED;
                        }
                        });
                        statement.finalize();
                    }
                    
                }
//                alert("add over!");
            }
            else if(parentNodes[i].nodeName === "recv_DEL")
            {
                
               
                for(var j = 0;j < childNodes.length;j ++)
                {
                    var emailId = childNodes[j].id;
                    statement = dDeviceSqlite.dbConnection.createStatement("\
                    DELETE FROM td_email WHERE eMessageId = :myId and eName = :myName");
                    statement.params.myId = emailId; 
                    statement.params.myName = aXml.split("_")[0]; 
//                    alert("delete emaiId: "+emailId);
                    try
                    {
                        while(statement.executeStep())
                        {   
                            continue;
                        }
                    }
                    finally
                    {
                        statement.reset();
                    }
//                    alert("delete over!");
                }
            }
//            alert(emailNodes[i].nodeName);
//            alert(emailNodes[i].childNodes.length);
        }
        filetmp.remove(true);
    }
    catch(e)
    {
        alert("error");
        filetmp.remove(true);
    }
        alert("overs sync...");
}

function backUpMsgToLocal()
{
    
    //alert("备份信息到本地！");
    var treeTS=document.getElementById("deviceThreadTree");
    var idList = [];
    var rangeCount = treeTS.view.selection.getRangeCount();
    for (var i = 0; i < rangeCount; i++){
    var start = {};
    var end = {};
    treeTS.view.selection.getRangeAt(i, start, end);
    for (var c = start.value; c <= end.value; c++){
      var itemObj=treeTS.view.getItemAtIndex(c);
      var itemid=treeTS.view.getItemAtIndex(c).id;
      var dbName=itemObj.getAttribute("statustext");
      //alert(itemid+"=="+dbName);
      idList.push(itemid.split("_")[1]);
     }
    }
    dDeviceSqlite.onLoad();
    var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT aName  FROM td_account where aXml = :myVal");
                  statement.params.myVal = dbName;
                 
        try {
                 while (statement.executeStep()) {
                        var curAccName=statement.row.aName;
                      }
                   }
                 
        finally {
                  statement.reset();
                } 
              
    if(dk9Sqlite.onLoad(dbName))
    {
      //alert("me");
      var msgInfo=[{gsubject:"主题",gcontent:"内容"}];
      //alert("you");
      //alert("idList.length="+idList.length);
      for(var i=0;i<idList.length;i++)
      { 
       //alert(idList[i]);   
       var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT * FROM  messages WHERE id = :myVal");
       statement.params.myVal =idList[i];
       //alert(idList[i]);
       try{
         while(statement.executeStep())
         {
            var data1=statement.row.html_content;
            var data2=statement.row.subject;
            msgInfo.push({gcontent:data1,
                          gsubject:data2});
            //alert("a");          
         }
       }catch(e)
       {
           
       }
        finally
       {
        statement.reset();
        }
      }
   
    }
    //alert(msgInfo.length);
    Components.utils.import("resource://gre/modules/FileUtils.jsm");
    Components.utils.import("resource://gre/modules/NetUtil.jsm");
    //Components.utils.import("resource://gre/modules/FileUtils.jsm");
    var driName=curAccName.split("@")[0]+"_Message";
    var dir = FileUtils.getDir("Home", [driName], true);
    var dirPath=dir.path;
    //var file = new FileUtils.File(dirPath);
    for(var i=1;i<msgInfo.length;i++)
    {
    var file = new FileUtils.File(dirPath);    
    var fileName=msgInfo[i].gsubject+"_"+Date.now()+".html";
    file.append(fileName);
    
    var ostream = FileUtils.openSafeFileOutputStream(file);

    var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
                createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
    converter.charset = "UTF-8";
  
    var istream = converter.convertToInputStream(msgInfo[i].gcontent);
 
    NetUtil.asyncCopy(istream, ostream, function(status) {
    if (!Components.isSuccessCode(status)) {
    alert("写入数据错误");
    return;
  }else{
    //alert("write date success");
 }
});   
   }
   prompts.alert(null, "邮件备份", "邮件数据备份成功"+"\n"+"邮件所在路径："+dir.path);
   //alert("邮件数据备份成功"+"\n"+"邮件所在路径："+dir.path);
}